package com.lcf.common.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.util.Matrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PDFUtils {

    public static void toPng(String input) {
        File file = new File(input);
        try (
                PDDocument document = PDDocument.load(file);
        ) {
            PDFRenderer renderer = new PDFRenderer(document);
            BufferedImage bufferedImage = renderer.renderImageWithDPI(0, 72 * 2); // 将第一页转为图片
            String output = file.getParent()
                    + "/"
                    + file.getName().substring(0, file.getName().lastIndexOf("."))
                    + ".png";
            ImageIO.write(bufferedImage, "png", new File(output));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 给pdf添加水印
     *
     * @param input  : 输入
     * @param output : 输出
     * @param text   : 水印内容
     */
    public static void watermarkText(String input, String output, String text) {
        try (
                PDDocument document = PDDocument.load(new File(input));
        ) {
            // int pages = document.getNumberOfPages();
            document.getPages().forEach(pdPage -> {
                try (PDPageContentStream contentStream =
                             new PDPageContentStream(document, pdPage, PDPageContentStream.AppendMode.APPEND, true, true)) {
                    contentStream.setFont(PDType1Font.HELVETICA, 30); // 字体
                    contentStream.setNonStrokingColor(0.2); // 透明度
                    // 添加文本水印
                    contentStream.beginText();
                    contentStream.newLineAtOffset(100, 100); // 水印位置
                    contentStream.showText(text);
                    contentStream.endText();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            document.save(output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        watermarkText("C:\\Users\\Administrator\\Desktop\\绩效考核表\\李晨飞.pdf",
                "C:\\Users\\Administrator\\Desktop\\绩效考核表\\李晨飞-1.pdf", "water");

    }

}
